package process

import (
	"encoding/json"
	"fmt"
	"net"
	"testgin0012/chat/common"
)


type UserProcess struct {
}

func NewUserProcess() *UserProcess {
	return &UserProcess{}
}

func (userProcess *UserProcess) SayAll(conn net.Conn, request common.Request) (subMessage *common.RequestSayAll, err error) {
	subMessage = &common.RequestSayAll{}
	err = json.Unmarshal([]byte(request.Data), subMessage)
	if err != nil {
		err = fmt.Errorf("Message内层json.Unmarshal解码失败, err=%v\n", err)
		return
	}


	//user, err = common.FindUser(subMessage.UserId)
	//if err != nil {
	//	return
	//}
	//if user == nil {
	//	err = fmt.Errorf("用户:%v不存在\n", subMessage.UserId)
	//	return
	//}
	return
}

func (userProcess *UserProcess) Login(conn net.Conn, request common.Request) (user *common.User, err error) {
	subMessage := common.RequestRegister{}
	err = json.Unmarshal([]byte(request.Data), &subMessage)
	if err != nil {
		err = fmt.Errorf("Message内层json.Unmarshal解码失败, err=%v\n", err)
		return
	}
	user, err = common.FindUser(subMessage.UserId)
	if err != nil {
		return
	}
	if user == nil {
		err = fmt.Errorf("用户:%v不存在\n", subMessage.UserId)
		return
	}
	return
}
func (userProcess *UserProcess) Register(conn net.Conn, request common.Request) (res string, err error) {
	subMessage := common.RequestRegister{}
	err = json.Unmarshal([]byte(request.Data), &subMessage)
	if err != nil {
		err = fmt.Errorf("Message内层json.Unmarshal解码失败, err=%v\n", err)
		return
	}
	user, err := common.FindUser(subMessage.UserId)
	if err != nil {
		return
	}
	if user != nil {
		err = fmt.Errorf("用户:%v已存在\n", subMessage.UserId)
		return
	}
	user, err = common.CreateUser(subMessage.UserId, subMessage.PassWord, subMessage.NickName)
	if err != nil {
		err = fmt.Errorf(fmt.Sprintf("用户创建失败, err=%s\n", err))
		return
	}
	res = "注册成功"
	return
}
